<?php

namespace App\Models;

use App\Constant\ThirdMoneyCode;
use App\Exceptions\GeneralException;
use App\Library\Traits\RepaySmsRemind;
use App\ModelFilters\RepaySummaryFilter;
use App\Models\Traits\PayCompensate;
use App\Models\Traits\Repay as RepayTrait;
use Carbon\Carbon;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use App\Models\Traits\RepaySummary as RepaySummaryTrait;
use App\Models\Traits\OldRepaySummary as OldRepaySummaryTrait;
use App\Models\Traits\RepaySummaryInteface;
use App\Models\Traits\RepayInfo as RepayInfoTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\RepaySummary
 *
 * @property int $id
 * @property int $uid 当前用户
 * @property int $loan_id 放款id
 * @property int $amount 总金额存分
 * @property int $period_count 总期数
 * @property int $period 当前的期数(0代表换不还清)
 * @property string $rate 后台配置,保存json
 * @property string 老卡贷放款id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereLoanId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary wherePeriod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary wherePeriodCount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property int $loan_request_id 授信申请表id
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecord[] $recordMany
 * @property-read \App\Models\RepayRecord $recordOne
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary filter($input = array(), $filter = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary paginateFilter($perPage = null, $columns = array(), $pageName = 'page', $page = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary simplePaginateFilter($perPage = null, $columns = array(), $pageName = 'page', $page = null)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereBeginsWith($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereEndsWith($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereLike($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereLoanRequestId($value)
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecordCommon[] $common
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecordMoney[] $money
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RepayRecordMonth[] $month
 * @property int $status 状态(1 进行中 2 完成还款)
 * @property int $current_repay 当前用户的对应的当前还款
 * @property-read \App\Models\LoanApply $relationLoanApply
 * @property-read \App\Models\UserLoanRequest $relationUserLoanRequests
 * @property-read \App\Models\User $users
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereCurrentRepay($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereStatus($value)
 * @property int $data_type 新旧卡贷标识: 1: 新卡贷数据, 2:旧卡贷数据
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\RepaySummary whereDataType($value)
 */
class RepaySummary extends Model
{
    use Filterable, RepayTrait,RepaySummaryTrait,RepayInfoTrait,RepaySmsRemind,OldRepaySummaryTrait,RepaySummaryInteface;

    // 商户代偿（销账）功能 trait 包
    use PayCompensate;

    //current_repay 1当前记录, 0以前记录
    const CURRENT_REPAY_ZERO = 0;
    const CURRENT_REPAY_ONE = 1;

    //状态(1 进行中 2 完成还款)
    const STATUS_ONE = 1;
    const STATUS_TWO = 2;

    //资方接口和公共接口请求次数
    const MONEY_API_NUMBER = 10;
    const COMMON_API_NUMBER = 20;

    const MONEY_API = 'money';
    const COMMON_API = 'common';

    const FINES_RATE = 0.005;//农信罚息费率 默认千分之五

    //新旧卡贷标识: 1: 新卡贷数据, 2:旧卡贷数据
    const DATA_TYPE_ONE = 1;
    const DATA_TYPE_TWO = 2;

    //是否推送  0 未推送  1推送
    const UP_TYPE_ZERO = 0;
    const UP_TYPE_ONE = 1;

    //区分快闪卡贷版本0=>kskd-2,1:=>kskd,2=>kskd-1,3=>没数据的
    const KSKD_REPAY_TYPE_ZERO=0;
    const KSKD_REPAY_TYPE_ONE=1;
    const KSKD_REPAY_TYPE_TWO=2;
    const KSKD_REPAY_TYPE_THREE=3;


    //后台放款用户列表的赛选状态
    static $FULL_STATUS = [
        RepaySummary::STATUS_ONE => '还款中',
        RepaySummary::STATUS_TWO    => '还款完成',
    ];

    static $FULL_STATUS_DETAIL = [
        RepaySummary::STATUS_ONE => [
            RepayRecordMoney::TYPE_ONE           => '待还',
            RepayRecordMoney::TYPE_FIVE          => '逾期',
        ],
        RepaySummary::STATUS_TWO => [
            RepayRecordMoney::TYPE_TWO           => '逐期还款',
            RepayRecordMoney::TYPE_FOUR          => '余期还清',
        ],
    ];

    /**
     * 应该被转换成原生类型的属性。
     *
     * @var array
     */
    protected $casts = [
        'rate' => 'array',
    ];

    /**
     * 不可被批量赋值的属性。
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * 定义默认模型过滤器
     *
     * @return string
     */
    public function modelFilter()
    {
        return $this->provideFilter(RepaySummaryFilter::class);
    }


    /**
     * Description:和具体的期数一对多
     * Author:lijiafei
     */
    public function recordMany(){
        return $this->hasMany(RepayRecord::class,'summary_id','id')->orderBy('period','asc');
    }

    /**
     * Description:和具体的期数一对一
     * Author:lijiafei
     */
    public function recordOne(){
        //查询第一个不成功的记录
        return $this->hasOne(RepayRecord::class,'summary_id','id')->orderBy('period','asc');
    }

    /**
     * Description: relation一条记录
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function relationProcessingRecord() {
        return $this->hasOne(RepayRecord::class,'summary_id','id');
    }

    /**
     * Description: 关联资金记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function money()
    {
        return $this->hasMany('App\Models\RepayRecordMoney','summary_id','id');
    }

    public function singleMoney()
    {
        return $this->hasMany('App\Models\RepayRecordMoney','summary_id','id')->where('period','>','0');
    }

    /**
     * Description: 关联资金记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function month()
    {
        return $this->hasMany('App\Models\RepayRecordMonth','summary_id','id');
    }

    /**
     * Description: 关联公共记录表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function common()
    {
        return $this->hasMany('App\Models\RepayRecordCommon','summary_id','id');
    }

    /**
     * Description: 关联用户放款信息表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function relationLoanApply()
    {
        return $this->hasOne('App\Models\LoanApply', 'loan_request_id', 'loan_request_id');
    }

    /**
     * Description: 关联用户放款信息表
     * Author: Gxs
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function relationUserLoanRequests()
    {
        return $this->hasOne('App\Models\UserLoanRequest', 'id', 'loan_request_id');
    }

    public function users(){
        return $this->belongsTo('App\Models\User','uid','id');
    }


    /**
     * Description: 设置资方记录利息费
     * Author: Gxs
     * @param $value
     */
    public function setAmountAttribute($value)
    {
        $this->attributes['amount'] = (int)bcmul($value, 100);
    }

    /**
     * Description: 获取资方记录利息费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getAmountAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }


    /**
     * 限制查询正在进行中的还款
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeDoing($query)
    {
        return $query->where('status', '=', self::STATUS_ONE);
    }

    /**
     * Description: 初始化还款记录数据
     * Author: Gxs
     * @param LoanApply $apply 完整模型数据
     * @return bool|string
     * @throws GeneralException
     */
    public static function initRepaySummary(LoanApply $apply)
    {
        $user_id = $apply->user_id;
        $loan_id = $apply->loan_id;
        $loan_info = self::where(['uid' => $user_id,'status' => self::STATUS_ONE,])->first();


        if (!empty($loan_info)) {
            Log::debug('repay_init_record', ['message' => '存在未还款的记录']);
            return '存在未还款的记录';
        }
        $loan_info = self::where(['uid' => $user_id,'loan_id' => $loan_id,])->first();

        if (!empty($loan_info)) {
            Log::debug('repay_init_record', ['message' => '还款记录初始化数据已存在']);
            return '还款记录初始化数据已存在';
        }


        //调用还款计划表
        if (!$repay_plan_data = self::mapMoneyDataFromThirdApi($loan_id))

            return ThirdMoneyCode::REPAY_PLAN_ERROR_MESSAGE;

        try {
            DB::beginTransaction();
            self::where([
                ['uid', '=', $user_id],
                ['current_repay', '=', self::CURRENT_REPAY_ONE],
            ])->update(['current_repay' => self::CURRENT_REPAY_ZERO]);
            $create = self::parseDataFromLoanApplyModel($apply);
//            $summary_model = RepaySummary::where('loan_id', $apply['loan_id'])->first();
            $summary_model = self::create($create);
            //$repay_plan_data 必须为 period asc 排列, 若接口返回不符合需自己处理
            $record_result = self::parseRecordDataFromRepayPlan($repay_plan_data, $apply, $summary_model);
            if (true == $record_result['one']) {
                $record_model = $summary_model->recordMany()->create($record_result['data']);
                $record_data = $record_model->order('period asc')->toArray();
                $month_data = self::parseMonthDataFromRecord($record_data, $summary_model); //月保
                $summary_model->month()->create($month_data['data']);
                $record_money = self::parseMoneyDataFromRepayPlan($repay_plan_data, $record_data); //资方
                $summary_model->money()->create($record_money['data']);
                $common_data = self::parseCommonDataFromRecord($record_data, $record_money['data'], $summary_model); //公共 = 合计 - 资方的
                $summary_model->common()->create($common_data['data']);

            } else {
                $record_model = $summary_model->recordMany()->createMany($record_result['data']);
                $record_data = $record_model->toArray();
                $month_data = self::parseMonthDataFromRecord($record_data, $summary_model); //月保
                $summary_model->month()->createMany($month_data['data']);
                $record_money = self::parseMoneyDataFromRepayPlan($repay_plan_data, $record_data); //资方
                $summary_model->money()->createMany($record_money['data']);
                $common_data = self::parseCommonDataFromRecord($record_data, $record_money['data'], $summary_model); //公共 = 合计 - 资方的
                $summary_model->common()->createMany($common_data['data']);
            }

            //更新用户全局状态
            UserGlobal::where('uid',$user_id)->update(['global_status' => UserGlobal::STATUS_REPAY_INIT]);
            Log::debug('repay_init_record', ['message' => '初始化还款数据成功']);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('repay_init_failure', [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
            ]);
            throw new GeneralException($e->getMessage());
        }
        return true;
    }

    /**
     * Description: 根据loan_request_id获取订单APP显示信息
     * Author: Gxs
     * @param $loan_request_id
     * @return array
     */
    public static function getSingleFrontRepayInfo($loan_request_id)
    {
        $summary = self::where('loan_request_id', $loan_request_id)
            ->with(['relationLoanApply' => function ($query) {
                $query->select(['loan_request_id','loan_time','trans_money_list', 'created_at']);
            }])
            ->first();
        if(!$summary){
            return [];
        }
        $result = self::parseHistoryInfo($summary);
        return $result;
    }

    /**
     * 获取前端历史记录列表
     *
     * @param array $params
     * @param int $page_size
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public static function getFrontHistoryList($params, $page_size = 0)
    {
        $order_field = 'created_at';
        $order_sort = 'desc';
        if (0 === $page_size) {
            $list = self::filter($params)
                ->with(['relationLoanApply' => function ($query) {
                    $query->select(['loan_request_id','loan_time','trans_money_list', 'created_at']);
                }])
                ->orderBy($order_field,$order_sort)
                ->get();
            $total = (int)$list->count();
            $result = [
                'list' => $list,
                'total' => $total,
            ];
        } else {
            $list = self::filter($params)
                ->with(['relationLoanApply' => function ($query) {
                    $query->select(['loan_request_id','loan_time','trans_money_list', 'created_at']);
                }])
                ->orderBy($order_field, $order_sort)
                ->paginate($page_size);
            $result = [
                'list' => $list->items(),
                'total' => $list->total(),
            ];
        }
        return $result;
    }

    /**
     * Description: 订单历史记录列表处理
     * Author: Gxs
     * @param Collection $list
     * @return array|bool
     */
    public static function parseHistoryList($list)
    {
        $result = [];
        foreach ($list as $key=>$value) {
            $temp = self::parseHistoryInfo($value);
            $result[] = $temp;
        }
        return $result;
    }

    /**
     * Description: 提前结清验证数据
     * Author: tianping
     * @param array $data 接口请求数据
     * @return array|bool
     */
    public function verifyAllRepay($data){
        $summaryInfo=$this;
        if($summaryInfo->status == RepaySummary::STATUS_TWO){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前还款数据已还清';
            return collectionResp($returnData);
        }
        $summaryOneInfo = self::getRepaySummaryLog($summaryInfo->uid);
        $result = $this->verifyData($summaryOneInfo);
        if($result['result'] == CollectionApiRequest::RESPONSE_OTHER_ERROR){
            return collectionResp($result);
        }
        //获取全部还清的时候的记录 period = 0的记录
        $info = self::getAllRepayLog($summaryOneInfo->id,$summaryOneInfo->uid);
        if(!$info){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '提前结清失败';
            return collectionResp($returnData);
        }
        if($info->recordOne->status == RepayRecord::STATUS_TWO){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '正在还款中,不能重复发起';
            return collectionResp($returnData);
        }
        $isSave = RepaySummary::saveBankInfo($summaryOneInfo->recordOne->bank_cards_id,$summaryOneInfo->uid);
        if($isSave === false){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '还款失败,请稍后重试';
            return collectionResp($returnData);
        }
        $flag = self::checkApi($info->recordOne->summary_id,$info->recordOne->uid);
        if(!$flag){
            $returnData['status']=false;


            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当日请求次数已达上限';
            return collectionResp($returnData);
        }
        RepayRecord::saveApplyNumber($data['applyNumber'],$info->recordOne->id);
        return collectionResp(['status'=>true,'result'=>$info->recordOne]);
    }

    /**
     * Description: 单笔代扣验证
     * Author: tianping
     * @param array $data 接口请求数据
     * @return array|bool
     * @throws GeneralException
     */
    public function verifySingleRepay($data){
        //获取当前应该还哪期的数据
        $repayInfo = RepaySummary::getRepaySummaryLog($this->uid);
        if(!$repayInfo){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前没有还款计划';
            return collectionResp($returnData);
        }

        if($repayInfo->recordOne->status == RepayRecord::STATUS_TWO){
            //代表这条记录还在轮询中,不要还款
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '正在还款中,不能发起新的还款';
            return collectionResp($returnData);
        }
         //判断是否有全部还清这条记录,如果有返回false
        $isCurrentRepay = RepaySummary::isCurrentRepay($repayInfo->id);
        if(!$isCurrentRepay){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前不能进行逐期还款';
            return collectionResp($returnData);
        }


        $flag = RepaySummary::checkApi($repayInfo->recordOne->summary_id,$repayInfo->recordOne->uid);
        if(!$flag){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当日请求次数已达上限';
            return collectionResp($returnData);
        }
         return ['status'=>true,'result'=>$repayInfo->recordOne];
    }

    /**
     * Description: 多笔代扣验证
     * Author: tianping
     * @param array $data 接口请求数据
     * @return array|bool
     * @throws GeneralException
     */
    public function verifyMultipleRepay($data){
        $summaryInfo=$this;
        $flag = RepaySummary::checkApi($summaryInfo->id,$summaryInfo->uid);
        if(!$flag){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当日请求次数已达上限';
            return collectionResp($returnData);
        }
        $periods=explode(',',$data['period']);
        $repayReCords=RepayRecord::where('summary_id',$summaryInfo->id)->whereIn('period',$periods)->get();
        foreach($repayReCords as $repayReCord){
            if($repayReCord->status == RepayRecord::STATUS_TWO){
                //代表这条记录还在轮询中,不要还款
                $returnData['status']=false;
                $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
                $returnData['msg'] = '正在还款中,不能发起新的还款';
                return collectionResp($returnData);
            }
        }
        return collectionResp(['status'=>true,'result'=>$repayReCords]);
    }

    public function verifyData(RepaySummary $summaryInfo){
        //判断是否有逾期的记录
        $day_number = count_days(Carbon::now()->toDateString(),$summaryInfo->recordOne->normal_date);
        if($day_number > 0){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前还款记录有逾期记录,不能全部结清';
            return $returnData;
        }
        //判断当前银行卡是否有效
        $hold_agreement_num = UserBankCard::getHoldAgreementNumById($summaryInfo->recordOne->bank_cards_id,$summaryInfo->id);
        if(!$hold_agreement_num){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '用户的银行卡协议号有误';
            return $returnData;
        }
        if($summaryInfo === false){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '未查询到还款记录';
            return $returnData;
        }
        if($summaryInfo->recordOne->status == RepayRecord::STATUS_TWO){
            $returnData['status']=false;
            //代表这条记录还在轮询中,不要还款
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '正在还款中,不能全部结清';
            return $returnData;
        }
        //判断是否可以全部还清
        $isAllRepay = RepaySummary::isAllRepay($summaryInfo->recordOne);
        if(!$isAllRepay){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前状态不能进行提前结清';
            return $returnData;
        }
        return ['result' => CollectionApiRequest::RESPONSE_OK];
    }







    /*
     * Description: 订单历史记录信息处理
     * Author: Gxs
     * @param RepaySummary $value
     * @return array
     */
    public static function parseHistoryInfo($value)
    {
        Log::debug('repay_history', ['value' => $value]);
        $pay_order_number = 0;
        if (!empty($value->relationLoanApply->trans_money_list)) {
            $pay_order_number = self::getPayOrderNo($value->relationLoanApply->trans_money_list); //获取投保单号-_-
        }
        Log::debug('repay_history', [
            'value_id' => $value->id,
            'uid' => auth('api')->user()->getAuthIdentifier(),
        ]);

        $temp = [
            'id' => $value->id,
            'period_count' => $value->period_count, //总期数
            'loan_time' => empty($value->relationLoanApply->loan_time) ? Carbon::createFromTimeString($value->relationLoanApply->created_at)->format('Y·m·d') : Carbon::createFromTimeString($value->relationLoanApply->loan_time)->format('Y·m·d'), //借款日期
            'pay_order_number' => $pay_order_number, //获取投保单号-_-
            'amount' => $value->amount, //借款本金
        ];
        //获取当前次 最新期的 每期应还, 还款状态
        if (RepaySummary::STATUS_TWO == $value->status) {
            $current_where = [
                ['summary_id', '=', $value->id],
                ['period', '<>', 0],
            ];
            $current_order = 'desc';
        } else {
            $current_where = [
                ['summary_id', '=', $value->id],
                ['period', '<>', 0],
                ['status', '<>', RepayRecord::STATUS_FOUR],
            ];
            $current_order = 'asc';
        }
        $current_record = RepayRecord::where($current_where)->orderBy('normal_date', $current_order)->first();
        if (!empty($current_record)) {
            $lending_amount = bcadd($current_record->common->lending_money, $current_record->money->lending_money, 2); //总利息
            $manage_amount = bcadd($current_record->common->manage_money, $current_record->money->manage_money, 2); //总管理费
            $repay_amount = bcadd(bcadd(bcadd($lending_amount, $manage_amount, 2), $current_record->month->amount, 2), $current_record->amount, 2); //本期应还 = 实还金额
            $get_result_result = self::getOtherMoneyAndType($value, $current_record);
            $type = $get_result_result['type'];
            $fines_amount = $get_result_result['fines_amount'];
            $pay_off_amount = $get_result_result['pay_off_amount'];
            $overdue_day = $get_result_result['overdue_day'];
            $repay_amount = bcadd(bcadd($fines_amount, $pay_off_amount, 2), $repay_amount, 2);
            $temp['period'] = $current_record->period; //当前期数
            $temp['type'] = $type;
            $temp['repay_amount'] = $repay_amount; //应还金额(包含罚息)
            $temp['fines_amount'] = $fines_amount;//罚息
            $temp['overdue_day'] = $overdue_day;//逾期天数
        } else {
            Log::debug('repay_history_index', ['message' => '未找到历史记录的最新期数据', 'current_where' => $current_where]);
            $temp['period'] = 1; //当前期数
            $temp['type'] = RepayRecord::RETURN_TYPE_ONE;
            $temp['repay_amount'] = '0.00';
            $temp['fines_amount'] = '0.00';
            $temp['overdue_day'] = 0;
        }
        return $temp;
    }

    /**
     * 是否全部还清
     * @author lvyinhong
     * @param $repaySummary
     * @return bool
     */
    public static function isPayOff($repaySummary)
    {
        if ($repaySummary instanceof self) {
           return intval($repaySummary->period) === 0;
        }
        return false;
    }

    /**
     * 验证是否符合全部销账
     * @param $data
     * @return array
     */
    public function verifyAllWriteOff($data){
        $summaryInfo=$this;
        if($summaryInfo->status == RepaySummary::STATUS_TWO){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前还款已还清';
            return collectionResp($returnData);
        }
        // 先查看 repayRecord 里有没有是否 在进行中且有逾期的 还款计划
        $record = RepayRecord::where(
            [
                'summary_id' => $summaryInfo->id,
                'uid' => $summaryInfo->uid,
                'status' => 1
            ])->where('normal_date', '<', date('Y-m-d'))
            ->first();
        if($record) {
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当前有逾期未还的，不能销账!';
        }
        $summaryOneInfo = self::getAllRepayLog($summaryInfo->id,$summaryInfo->uid);
        $result = $this->verifyData($summaryOneInfo);
        if($result['result'] == CollectionApiRequest::RESPONSE_OTHER_ERROR){
            return collectionResp($result);
        }
        //获取全部还清的时候的记录 period = 0的记录
        if(!$summaryOneInfo){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '提前结清失败';
            return collectionResp($returnData);
        }
        if($summaryOneInfo->recordOne->status == RepayRecord::STATUS_TWO){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '正在还款中,不能重复发起';
            return collectionResp($returnData);
        }
        $isSave = RepaySummary::saveBankInfo($summaryOneInfo->recordOne->bank_cards_id,$summaryOneInfo->uid);
        if($isSave === false){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '还款失败,请稍后重试';
            return collectionResp($returnData);
        }
        $flag = self::checkApi($summaryOneInfo->recordOne->summary_id,$summaryOneInfo->recordOne->uid);
        if(!$flag){
            $returnData['status']=false;
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '当日请求次数已达上限';
            return collectionResp($returnData);
        }
        RepayRecord::saveApplyNumber($data['applyNumber'],$summaryOneInfo->recordOne->id);
        return ['status'=>true,'result'=>$summaryOneInfo->recordOne];
    }

    /**
     * Description: 获取是否为晋商资方渠道
     * Author: Gxs
     * @param $summary_id
     * @return bool true 晋商, false 其他
     */
    public static function getLoanChannel($summary_id)
    {
        $summary_model = RepaySummary::find($summary_id);
        if(self::DATA_TYPE_ONE == $summary_model->data_type){
            return true;
        }
        if ('LCC201709190010' == $summary_model->loan_channel)
            return true; //晋商 || 新光大
        else
            return false;
    }

    /**
     * Description:通过loan_id获取是否是新旧商户
     * Author:lijiafei
     * @param $loanId
     * @return int|mixed
     */
    public static function getDataTypeByLoanId($loanId){
        return RepaySummary::DATA_TYPE_ONE;//因为蔚商和新流的京东协议共享,所以可以直接使用新的商户扣
        $summaryInfo = self::select(['data_type'])->where('loan_id',$loanId)->first();
        if($summaryInfo){
            return $summaryInfo->data_type;
        }else{
            return RepaySummary::DATA_TYPE_ONE;
        }
    }

    /**
     * Description:获取龙信和老光大的已还金额
     * Author: Mmy
     * DateTime: 2019-03-19 13:10
     * @param $record
     * @return array
     */
    public static function getYihuanMoneyForOldData($record)
    {
        $common_status = $record->common->status;
        $month_status = $record->month->status;
        $amount = 0;
        $lending_money = 0;
        $manage_money = 0;
        $common_fines_money = 0;
        $month_money = 0;
        if ($common_status == RepayRecordCommon::STATUS_FOUR) {
            $amount = bcadd($amount,$record->amount,2);
            $lending_money = bcadd($lending_money,$record->common->lending_money,2);
            $common_fines_money = bcadd($common_fines_money,$record->common->fines_money,2);
            $manage_money = bcadd($manage_money,$record->common->manage_money,2);
        }
        if($month_status == RepayRecordMonth::STATUS_FOUR){
            $month_money = bcadd($month_money,$record->month->amount,2);
        }
        //判断是否是有全部结清
        $common_repayment_money = 0;
        if($record->pay_off == RepayRecord::PAY_OFF_TWO){
            if($record->common->status == RepayRecordCommon::STATUS_FOUR){
                $common_repayment_money = $record->common->where('status',RepayRecordMoney::STATUS_FOUR)->where('period','<>',0)->sum('repayment_money');
                $common_repayment_money = bcdiv($common_repayment_money,100,2);
            }
        }
        $returnData = [
            'amount' => $amount,//已还本金
            'lending_money' => $lending_money,//已还利息
            'manage_money' => $manage_money,//已还贷后管理费
            'money_fines_money' => 0,//已还资方罚息
            'common_fines_money' => $common_fines_money,//已还公共罚息
            'month_money' => $month_money,//已还月保费
            'money_repayment_money' => 0,//如果是提前结清,已还资方提前结清手续费
            'common_repayment_money' => $common_repayment_money,//如果是提前结清,已还平台提前结清手续费
        ];
        //已还总金额
        $returnData['all_money'] = $returnData['amount'] + $returnData['lending_money'] + $returnData['manage_money'] + $returnData['money_fines_money'] + $returnData['common_fines_money'] + $returnData['month_money'];

        return $returnData;
    }

    /**
     * Description: 获取订单唯一标识 loan_id
     * Author:tianp
     * @param
     * @return string|mixed
     */
    public function getCaseCode()
    {
        return $this->loan_id;
    }


    /**
     * 销账的改变用户的单期状态
     */
    public static function setRepayCurrentStatus(RepayRecord $model,$money){
        //改变repay_summary表,repay_records,repay_record_money,repay_record_month,repay_record_money
        $repayMoney = \App\Models\RepaySummary::getRepayMoney($model);

        $all_money = $repayMoney['all_money'];
        $balance = bcsub($all_money,$money,2);
        $updateRecord = [
            'status' => RepayRecord::STATUS_FOUR,
            'repay_date' => Carbon::now()->toDateString(), //实际还款日期
            'repay_type' => RepayRecord::REPAY_TYPE_ACCOUNT,//状态改为销账
        ];
        $updateMoney = [
            'status' => RepayRecord::STATUS_FOUR,
            'apply_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'status_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'repay_date' => Carbon::now()->toDateString(), //实际还款日期
            'repay_type' => RepayRecord::REPAY_TYPE_ACCOUNT,//状态改为销账
            'fines_money' => bcmul($repayMoney['money_fines_money'],100),//资方罚息

        ];
        $updateMonth = [
            'status' => RepayRecord::STATUS_FOUR,
            'apply_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'status_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'repay_type' => RepayRecord::REPAY_TYPE_ACCOUNT,//状态改为销账
        ];
        $updateCommon = [
            'status' => RepayRecord::STATUS_FOUR,
            'apply_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'status_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'repay_type' => RepayRecord::REPAY_TYPE_ACCOUNT,//状态改为销账
            'fines_money' => bcmul($repayMoney['common_fines_money'],100),//平台罚息
        ];
        if($balance > 0){
            //我们的金额比他们收的多,保存在record_common字段relief_amount金额
            $updateCommon['relief_amount'] = bcmul($balance,100);
        }elseif($balance < 0){
            //我们的金额比他们收的少,保存在溢缴金额中,records表的balance中
            $updateRecord['balance'] = bcmul($balance,100);
        }
        try {
            DB::beginTransaction();
            $period_count = $model->relationSummary->period_count;
            \Log::debug('setXiaoZhang', ['message' => print_r($period_count, true)]);
            //最后顺序队列单期还款调用逻辑
            if ($period_count == $model->period) {
                //最后一期还清
                RepaySummary::where('id', $model->summary_id)->update([
                    'period' => $model->period,
                    'status' => RepaySummary::STATUS_TWO,
                ]); //summary 摘要表 最终状态变更
            } else {
                RepaySummary::where('id', $model->summary_id)->update(['period'=>(int)($model->period + 1),]); //summary表
            }

            //记录总表
            RepayRecord::where('id', $model->id)->update($updateRecord);

            RepayRecordMoney::where('record_id', $model->id)->update($updateMoney);

            RepayRecordMonth::where('record_id', $model->id)->update($updateMonth);

            RepayRecordCommon::where('record_id', $model->id)->update($updateCommon);

            UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_SUCCESS]); //全局状态
            //单期所有数据成功发送短信
            RepaySmsRemind::sendHandleSuccessSms($model->money); //手动
            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::debug('set_xiaozhang_success', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
            return false;
        }
    }

}